/**
 * 图片优化和懒加载工具函数
 */

/**
 * 图片格式枚举
 */
export enum ImageFormat {
  WEBP = 'webp',
  AVIF = 'avif',
  JPEG = 'jpeg',
  PNG = 'png',
  SVG = 'svg',
}

/**
 * 图片尺寸配置
 */
export interface ImageSizeConfig {
  width: number;
  height?: number;
  quality?: number;
  format?: ImageFormat;
}

/**
 * 响应式图片断点
 */
export const RESPONSIVE_BREAKPOINTS = {
  xs: 320,
  sm: 640,
  md: 768,
  lg: 1024,
  xl: 1280,
  '2xl': 1536,
  '3xl': 1920,
  '4xl': 2560,
} as const;

/**
 * 检测浏览器支持的图片格式
 */
export function getSupportedImageFormat(): ImageFormat {
  if (typeof window === 'undefined') return ImageFormat.JPEG;

  // 检测AVIF支持
  const avifCanvas = document.createElement('canvas');
  avifCanvas.width = 1;
  avifCanvas.height = 1;
  if (avifCanvas.toDataURL('image/avif').indexOf('data:image/avif') === 0) {
    return ImageFormat.AVIF;
  }

  // 检测WebP支持
  const webpCanvas = document.createElement('canvas');
  webpCanvas.width = 1;
  webpCanvas.height = 1;
  if (webpCanvas.toDataURL('image/webp').indexOf('data:image/webp') === 0) {
    return ImageFormat.WEBP;
  }

  return ImageFormat.JPEG;
}

/**
 * 生成优化的图片URL
 */
export function generateOptimizedImageUrl(
  src: string,
  config: ImageSizeConfig
): string {
  // 如果是外部URL且不是Trae API，直接返回
  if (src.startsWith('http') && !src.includes('trae-api-us.mchost.guru')) {
    return src;
  }

  // 处理Trae API图片
  if (src.includes('trae-api-us.mchost.guru')) {
    const url = new URL(src);

    // 设置尺寸
    if (config.width) {
      url.searchParams.set('w', config.width.toString());
    }
    if (config.height) {
      url.searchParams.set('h', config.height.toString());
    }

    // 设置质量
    if (config.quality) {
      url.searchParams.set('q', config.quality.toString());
    }

    // 设置格式
    if (config.format) {
      url.searchParams.set('f', config.format);
    }

    return url.toString();
  }

  // 本地图片处理（可以扩展为CDN处理）
  return src;
}

/**
 * 生成响应式图片srcSet
 */
export function generateResponsiveSrcSet(
  src: string,
  sizes: number[],
  quality = 75,
  format?: ImageFormat
): string {
  return sizes
    .map(size => {
      const optimizedUrl = generateOptimizedImageUrl(src, {
        width: size,
        quality,
        format,
      });
      return `${optimizedUrl} ${size}w`;
    })
    .join(', ');
}

/**
 * 生成sizes属性
 */
export function generateSizesAttribute(
  breakpoints: Record<string, string>
): string {
  const entries = Object.entries(breakpoints);
  const mediaQueries = entries.slice(0, -1).map(([breakpoint, size]) => {
    const width =
      RESPONSIVE_BREAKPOINTS[breakpoint as keyof typeof RESPONSIVE_BREAKPOINTS];
    return `(max-width: ${width}px) ${size}`;
  });

  // 添加默认尺寸
  const defaultSize = entries[entries.length - 1][1];
  mediaQueries.push(defaultSize);

  return mediaQueries.join(', ');
}

/**
 * 生成模糊占位符数据URL
 */
export function generateBlurDataURL(
  width = 10,
  height = 10,
  color = '#f3f4f6'
): string {
  const svg = `
    <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
      <defs>
        <linearGradient id="g" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stop-color="${color}"/>
          <stop offset="100%" stop-color="${adjustBrightness(color, -10)}"/>
        </linearGradient>
      </defs>
      <rect width="100%" height="100%" fill="url(#g)"/>
    </svg>
  `;

  return `data:image/svg+xml;base64,${btoa(svg)}`;
}

/**
 * 调整颜色亮度
 */
function adjustBrightness(hex: string, percent: number): string {
  const num = parseInt(hex.replace('#', ''), 16);
  const amt = Math.round(2.55 * percent);
  const R = (num >> 16) + amt;
  const G = ((num >> 8) & 0x00ff) + amt;
  const B = (num & 0x0000ff) + amt;

  return (
    '#' +
    (
      0x1000000 +
      (R < 255 ? (R < 1 ? 0 : R) : 255) * 0x10000 +
      (G < 255 ? (G < 1 ? 0 : G) : 255) * 0x100 +
      (B < 255 ? (B < 1 ? 0 : B) : 255)
    )
      .toString(16)
      .slice(1)
  );
}

/**
 * 预加载关键图片
 */
export function preloadCriticalImages(urls: string[]): Promise<void[]> {
  const promises = urls.map(url => {
    return new Promise<void>(resolve => {
      const img = new Image();
      img.onload = () => resolve();
      img.onerror = () => resolve(); // 即使失败也resolve，避免Promise.all失败
      img.src = url;
    });
  });

  return Promise.all(promises);
}

/**
 * 检测图片是否在视口中
 */
export function createImageObserver(
  callback: (entry: IntersectionObserverEntry) => void,
  options: IntersectionObserverInit = {}
): IntersectionObserver {
  const defaultOptions: IntersectionObserverInit = {
    rootMargin: '50px',
    threshold: 0.1,
    ...options,
  };

  return new IntersectionObserver(entries => {
    entries.forEach(callback);
  }, defaultOptions);
}

/**
 * 获取图片的主要颜色（用于占位符）
 */
export function extractDominantColor(imageUrl: string): Promise<string> {
  return new Promise((resolve, reject) => {
    const img = new Image();
    img.crossOrigin = 'anonymous';

    img.onload = () => {
      try {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');

        if (!ctx) {
          resolve('#f3f4f6');
          return;
        }

        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);

        const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
        const data = imageData.data;

        let r = 0,
          g = 0,
          b = 0;
        const pixelCount = data.length / 4;

        for (let i = 0; i < data.length; i += 4) {
          r += data[i];
          g += data[i + 1];
          b += data[i + 2];
        }

        r = Math.floor(r / pixelCount);
        g = Math.floor(g / pixelCount);
        b = Math.floor(b / pixelCount);

        const hex = `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;
        resolve(hex);
      } catch (error) {
        resolve('#f3f4f6');
      }
    };

    img.onerror = () => resolve('#f3f4f6');
    img.src = imageUrl;
  });
}

/**
 * 图片性能监控
 */
export interface ImagePerformanceMetrics {
  loadTime: number;
  fileSize?: number;
  format: string;
  dimensions: { width: number; height: number };
  memoryUsage?: {
    usedJSHeapSize: number;
    totalJSHeapSize: number;
    jsHeapSizeLimit: number;
  };
}

export function measureImagePerformance(
  imageElement: HTMLImageElement
): Promise<ImagePerformanceMetrics> {
  const startTime = performance.now();

  return new Promise<ImagePerformanceMetrics>(resolve => {
    const onLoad = () => {
      const loadTime = performance.now() - startTime;
      const metrics: ImagePerformanceMetrics = {
        loadTime,
        format: getImageFormat(imageElement.src),
        dimensions: {
          width: imageElement.naturalWidth,
          height: imageElement.naturalHeight,
        },
      };

      // 添加内存使用情况（如果可用）
      if ('memory' in performance) {
        const memory = (
          performance as Performance & {
            memory: {
              usedJSHeapSize: number;
              totalJSHeapSize: number;
              jsHeapSizeLimit: number;
            };
          }
        ).memory;
        metrics.memoryUsage = {
          usedJSHeapSize: memory.usedJSHeapSize,
          totalJSHeapSize: memory.totalJSHeapSize,
          jsHeapSizeLimit: memory.jsHeapSizeLimit,
        };
      }

      resolve(metrics);
      imageElement.removeEventListener('load', onLoad);
    };

    if (imageElement.complete) {
      onLoad();
    } else {
      imageElement.addEventListener('load', onLoad);
    }
  });
}

/**
 * 从URL获取图片格式
 */
function getImageFormat(url: string): string {
  const extension = url.split('.').pop()?.toLowerCase();
  return extension || 'unknown';
}

/**
 * 图片缓存管理
 */
export class ImageCache {
  private cache = new Map<string, HTMLImageElement>();
  private maxSize: number;

  constructor(maxSize = 50) {
    this.maxSize = maxSize;
  }

  /**
   * 添加图片到缓存
   */
  set(url: string, image: HTMLImageElement): void {
    if (this.cache.size >= this.maxSize) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }

    this.cache.set(url, image);
  }

  /**
   * 从缓存获取图片
   */
  get(url: string): HTMLImageElement | undefined {
    return this.cache.get(url);
  }

  /**
   * 检查图片是否在缓存中
   */
  has(url: string): boolean {
    return this.cache.has(url);
  }

  /**
   * 清空缓存
   */
  clear(): void {
    this.cache.clear();
  }

  /**
   * 获取缓存大小
   */
  size(): number {
    return this.cache.size;
  }
}

// 全局图片缓存实例
export const globalImageCache = new ImageCache();

/**
 * 常用的图片尺寸配置
 */
export const COMMON_IMAGE_SIZES = {
  thumbnail: { width: 150, height: 150, quality: 80 },
  small: { width: 300, height: 200, quality: 85 },
  medium: { width: 600, height: 400, quality: 85 },
  large: { width: 1200, height: 800, quality: 90 },
  hero: { width: 1920, height: 1080, quality: 90 },
  avatar: { width: 100, height: 100, quality: 90 },
  card: { width: 400, height: 250, quality: 85 },
  banner: { width: 1200, height: 300, quality: 90 },
} as const;

/**
 * 常用的响应式图片配置
 */
export const RESPONSIVE_IMAGE_CONFIGS = {
  hero: {
    sizes: '100vw',
    breakpoints: [640, 768, 1024, 1280, 1920],
    quality: 90,
  },
  card: {
    sizes: '(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw',
    breakpoints: [400, 600, 800],
    quality: 85,
  },
  thumbnail: {
    sizes: '150px',
    breakpoints: [150, 300],
    quality: 80,
  },
  gallery: {
    sizes: '(max-width: 768px) 50vw, (max-width: 1200px) 33vw, 25vw',
    breakpoints: [300, 400, 600, 800],
    quality: 85,
  },
} as const;
